import type { RouteMeta } from '../types/router';

// 用户信息接口
export interface UserInfo {
  id: string;
  username: string;
  roles: string[];
  permissions: string[];
  avatar?: string;
  nickname?: string;
}

// 获取当前用户信息
export const getCurrentUser = (): UserInfo | null => {
  const userStr = localStorage.getItem('userInfo');
  console.log('当前用户信息',userStr);
  if (!userStr) return null;
  
  try {
    return JSON.parse(userStr);
  } catch {
    return null;
  }
};

// 获取用户角色
export const getUserRoles = (): string[] => {
  const user = getCurrentUser();
  
  return user?.roles || [];
};

// 获取用户权限
export const getUserPermissions = (): string[] => {
  const user = getCurrentUser();
  return user?.permissions || [];
};

// 检查用户是否有指定角色
export const hasRole = (role: string): boolean => {
  const roles = getUserRoles();
  return roles.includes(role);
};

// 检查用户是否有任一指定角色
export const hasAnyRole = (roles: string[]): boolean => {
  const userRoles = getUserRoles();
  return roles.some(role => userRoles.includes(role));
};

// 检查用户是否有所有指定角色
export const hasAllRoles = (roles: string[]): boolean => {
  const userRoles = getUserRoles();
  return roles.every(role => userRoles.includes(role));
};

// 检查用户是否有指定权限
export const hasPermission = (permission: string): boolean => {
  const permissions = getUserPermissions();
  return permissions.includes(permission);
};

// 检查用户是否有任一指定权限
export const hasAnyPermission = (permissions: string[]): boolean => {
  const userPermissions = getUserPermissions();
  return permissions.some(permission => userPermissions.includes(permission));
};

// 检查用户是否有所有指定权限
export const hasAllPermissions = (permissions: string[]): boolean => {
  const userPermissions = getUserPermissions();
  return permissions.every(permission => userPermissions.includes(permission));
};

// 检查路由权限
export const checkRoutePermission = (meta: RouteMeta): boolean => {
  // 如果不需要认证，直接通过
  if (!meta.requiresAuth) return true;

  // 检查角色权限
  if (meta.roles && meta.roles.length > 0) {
    if (!hasAnyRole(meta.roles)) return false;
  }

  // 检查权限
  if (meta.permissions && meta.permissions.length > 0) {
    if (!hasAnyPermission(meta.permissions)) return false;
  }

  return true;
};

// 检查是否已登录
export const isAuthenticated = (): boolean => {
  const token = localStorage.getItem('token');
  const user = getCurrentUser();
  return !!(token && user);
};

// 登出
export const logout = (): void => {
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('refreshToken');
};

// 设置用户信息
export const setUserInfo = (userInfo: UserInfo): void => {
  localStorage.setItem('userInfo', JSON.stringify(userInfo));
};

// 设置认证令牌
export const setToken = (token: string): void => {
  localStorage.setItem('token', token);
};

// 获取认证令牌
export const getToken = (): string | null => {
  return localStorage.getItem('token');
};
